﻿using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace Admin.NET.Application;

/// <summary>
/// 设备上下线服务
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class DeviceOnOffLineService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<DeviceOnOffLine> _deviceOnOffLineRep;
    private readonly ILogger<DeviceOnOffLineService> logger;

    public DeviceOnOffLineService(SqlSugarRepository<DeviceOnOffLine> deviceOnOffLineRep,ILogger<DeviceOnOffLineService> logger)
    {
        _deviceOnOffLineRep = deviceOnOffLineRep;
        this.logger = logger;
    }

    /// <summary>
    /// 分页查询设备上下线
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Page")]
    [DisplayName("分页查询设备上下线")]
    public async Task<SqlSugarPagedList<DeviceOnOffLineOutput>> Page(PageDeviceOnOffLineInput input)
    {
        input.SearchKey = input.SearchKey?.Trim();
        var query = _deviceOnOffLineRep.AsQueryable()
            .WhereIF(!string.IsNullOrEmpty(input.SearchKey), u =>
                u.OffLineReason.Contains(input.SearchKey)
            )
            .WhereIF(input.DeviceId > 0, u => u.DeviceId == input.DeviceId)
            .WhereIF(input.GateWayId > 0, u => u.GateWayId == input.GateWayId)
            .WhereIF(!string.IsNullOrWhiteSpace(input.OffLineReason), u => u.OffLineReason.Contains(input.OffLineReason.Trim()))
            .WhereIF(input.IsOnline!=null,u=>u.IsOnline==input.IsOnline.Value)
            //处理外键和TreeSelector相关字段的连接
            .LeftJoin<DeviceInfo>((u, deviceid) => u.DeviceId == deviceid.Id)
            .LeftJoin<DeviceGateWay>((u, deviceid, gatewayid) => u.GateWayId == gatewayid.Id)
            .Select((u, deviceid, gatewayid) => new DeviceOnOffLineOutput
            {
                Id = u.Id,
                DeviceId = u.DeviceId,
                DeviceIdDeviceName = deviceid.DeviceName,
                GateWayId = u.GateWayId,
                GateWayIdGateWayName = gatewayid.GateWayName,
                IsOnline = u.IsOnline,
                OffLineReason = u.OffLineReason,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
            });
        return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 增加设备上下线
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Add")]
    [DisplayName("增加设备上下线")]
    public async Task<long> Add(AddDeviceOnOffLineInput input)
    {
        var entity = input.Adapt<DeviceOnOffLine>();
        await _deviceOnOffLineRep.CopyNew().InsertAsync(entity);
        return entity.Id;
    }
    public async Task<long> AddNoThrow(AddDeviceOnOffLineInput input)
    {
        try
        {
            return await Add(input);
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "");
            return 0;
        }
    }


    /// <summary>
    /// 删除设备上下线
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Delete")]
    [DisplayName("删除设备上下线")]
    public async Task Delete(DeleteDeviceOnOffLineInput input)
    {
        var entity = await _deviceOnOffLineRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _deviceOnOffLineRep.FakeDeleteAsync(entity);   //假删除
        //await _deviceOnOffLineRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 更新设备上下线
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Update")]
    [DisplayName("更新设备上下线")]
    public async Task Update(UpdateDeviceOnOffLineInput input)
    {
        var entity = input.Adapt<DeviceOnOffLine>();
        await _deviceOnOffLineRep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
    }

    /// <summary>
    /// 获取设备上下线
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "Detail")]
    [DisplayName("获取设备上下线")]
    public async Task<DeviceOnOffLine> Detail([FromQuery] QueryByIdDeviceOnOffLineInput input)
    {
        return await _deviceOnOffLineRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 获取设备上下线列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "List")]
    [DisplayName("获取设备上下线列表")]
    public async Task<List<DeviceOnOffLineOutput>> List([FromQuery] PageDeviceOnOffLineInput input)
    {
        return await _deviceOnOffLineRep.AsQueryable().Select<DeviceOnOffLineOutput>().ToListAsync();
    }

    /// <summary>
    /// 获取设备名称列表
    /// </summary>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "DeviceInfoDeviceIdDropdown"), HttpGet]
    [DisplayName("获取设备名称列表")]
    public async Task<dynamic> DeviceInfoDeviceIdDropdown()
    {
        return await _deviceOnOffLineRep.Context.Queryable<DeviceInfo>()
                .Select(u => new
                {
                    Label = u.DeviceName,
                    Value = u.Id
                }
                ).ToListAsync();
    }

    /// <summary>
    /// 获取网关名称列表
    /// </summary>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "DeviceGateWayGateWayIdDropdown"), HttpGet]
    [DisplayName("获取网关名称列表")]
    public async Task<dynamic> DeviceGateWayGateWayIdDropdown()
    {
        return await _deviceOnOffLineRep.Context.Queryable<DeviceGateWay>()
                .Select(u => new
                {
                    Label = u.GateWayName,
                    Value = u.Id
                }
                ).ToListAsync();
    }
}